package com.tools.bitbucket.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BashUtils {

    /**
     * 执行命令
     *
     * @param command
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public static String execCommand(String command, String dir) {
        String latestCommitId = "";
        String[] commands = command.split(" ");
        List<String> commandList = new ArrayList<>(commands.length);
        for (String s : commands) {
            if (StringUtils.isBlank(s)) {
                continue;
            }
            commandList.add(s);
        }
        commands = new String[commandList.size()];
        commands = commandList.toArray(commands);
        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        if (StringUtils.isNotBlank(dir)) {
            processBuilder.directory(new File(dir));
        }
        log.info("开始执行命令: {},执行路径： {} ", command, dir);
        Process exec = null;
        OutputHandlerRunnable outputHandlerRunnable = null;
        try {
            exec = processBuilder.start();
            // 获取外部程序标准输出流
            outputHandlerRunnable = new OutputHandlerRunnable(exec.getInputStream(), false, command, latestCommitId);
            new Thread(outputHandlerRunnable).start();
            // 获取外部程序标准错误流
            new Thread(new OutputHandlerRunnable(exec.getErrorStream(), true, command, latestCommitId)).start();
            int code = exec.waitFor();
            if(code != 0){
                log.error("命令: {},执行路径： {} , 执行结果: {}", command, dir, code);
            }else{
                log.info("命令: {},执行路径： {} , 执行结果: {}", command, dir, code);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("命令: {},执行路径： {} ,  执行结果: {}", command, dir, -1);
        }
        return outputHandlerRunnable.getLatestCommitId();
    }

    private static class OutputHandlerRunnable implements Runnable {
        private InputStream in;
        private String command;
        private String latestCommitId;
        private boolean error;

        public String getLatestCommitId() {
            return this.latestCommitId;
        }

        public OutputHandlerRunnable(InputStream in, boolean error, String command, String latestCommitId) {
            this.in = in;
            this.error = error;
            this.latestCommitId = latestCommitId;
            this.command = command;
        }

        @Override
        public void run() {
            try (BufferedReader bufr = new BufferedReader(new InputStreamReader(this.in))) {
                String line = null;
                while ((line = bufr.readLine()) != null) {
                    if ((line.startsWith("Cloning into")|| line.contains("50%")|| line.contains("100%"))) {
                        System.out.println(line);
                    }
                    if (this.command.equals("git rev-parse HEAD")) {
                        this.latestCommitId = line;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
